import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/comment.dart';
import '../services/comment_service.dart';
import '../services/websocket_manager.dart';

class CommentSection extends StatefulWidget {
  final int postId; // 帖子或内容ID
  final String postType; // 帖子类型：'community' 或 'technique'
  final Function(int)? onCommentCountChanged; // 评论数量变化回调

  const CommentSection({
    super.key,
    required this.postId,
    required this.postType,
    this.onCommentCountChanged,
  });

  @override
  State<CommentSection> createState() => CommentSectionState();
}

class CommentSectionState extends State<CommentSection> {
  List<Comment> _comments = [];
  final TextEditingController _commentController = TextEditingController();
  final CommentService _commentService = CommentService();
  final WebSocketManager _wsManager = WebSocketManager();
  bool _isLoading = true;
  bool _isSubmittingComment = false;
  bool _showEmojiPanel = false;
  bool _isKeyboardVisible = false;
  final FocusNode _focusNode = FocusNode();
  
  // 回复相关状态
  Comment? _replyingToComment;
  bool _isReplying = false;
  
  // 评论展开/折叠状态 - 记录每个父评论的展开状态
  Map<int, bool> _expandedComments = {};
  
  // 常用表情列表
  final List<String> _commonEmojis = [
    '😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣',
    '😊', '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰',
    '😘', '😗', '😙', '😚', '😋', '😛', '😝', '😜',
    '🤪', '🤨', '🧐', '🤓', '😎', '🤩', '🥳', '😏',
    '😒', '😞', '😔', '😟', '😕', '🙁', '☹️', '😣',
    '😖', '😫', '😩', '🥺', '😢', '😭', '😤', '😠',
    '😡', '🤬', '🤯', '😳', '🥵', '🥶', '😱', '😨',
    '😰', '😥', '😓', '🤗', '🤔', '🤭', '🤫', '🤥',
    '😶', '😐', '😑', '😬', '🙄', '😯', '😦', '😧',
    '😮', '😲', '🥱', '😴', '🤤', '😪', '😵', '🤐',
    '🥴', '🤢', '🤮', '🤧', '😷', '🤒', '🤕', '🤑',
    '🤠', '😈', '👿', '👹', '👺', '🤡', '💩', '👻',
    '💀', '☠️', '👽', '👾', '🤖', '🎃', '😺', '😸',
    '😹', '😻', '😼', '😽', '🙀', '😿', '😾', '👋',
    '🤚', '🖐️', '✋', '🖖', '👌', '🤌', '🤏', '✌️',
    '🤞', '🤟', '🤘', '🤙', '👈', '👉', '👆', '🖕',
    '👇', '☝️', '👍', '👎', '👊', '✊', '🤛', '🤜',
    '👏', '🙌', '👐', '🤲', '🤝', '🙏', '✍️', '💅',
    '🤳', '💪', '🦾', '🦿', '🦵', '🦶', '👂', '🦻',
    '👃', '🧠', '🫀', '🫁', '🦷', '🦴', '👀', '👁️',
    '👅', '👄', '💋', '🩸', '👶', '🧒', '👦', '👧',
  ];

  @override
  void initState() {
    super.initState();
    _loadComments();
    
    // 监听键盘状态
    _focusNode.addListener(() {
      setState(() {
        _isKeyboardVisible = _focusNode.hasFocus;
        if (_isKeyboardVisible) {
          _showEmojiPanel = false; // 键盘弹出时隐藏表情面板
        }
      });
    });
  }

  @override
  void dispose() {
    _commentController.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  void _loadComments() async {
    try {
      setState(() {
        _isLoading = true;
      });
      
      final result = await _commentService.getComments(
        postId: widget.postId,
        postType: widget.postType,
      );
      
      if (mounted) {
        setState(() {
          if (result['success'] == true && result['data'] != null) {
            final commentList = result['data'] as List;
            
            _comments = commentList.map((item) {
              // 检查数据类型，如果已经是Comment对象则直接使用，否则解析JSON
              Comment comment;
              if (item is Comment) {
                comment = item;
              } else {
                comment = Comment.fromJson(item as Map<String, dynamic>);
              }
              
              // 数据验证：如果parentId等于自己的id，则将其设为null（视为父评论）
              if (comment.parentId != null && comment.parentId == comment.id) {
                // 创建一个新的Comment对象，将parentId设为null
                comment = Comment(
                  id: comment.id,
                  techniqueId: comment.techniqueId,
                  userId: comment.userId,
                  content: comment.content,
                  likeCount: comment.likeCount,
                  status: comment.status,
                  createTime: comment.createTime,
                  isLiked: comment.isLiked,
                  parentId: null, // 明确设置为null
                  user: comment.user,
                  replies: comment.replies,
                );
              }
              
              return comment;
            }).toList();
            
            
            
          } else {
            _comments = [];
          }
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _comments = [];
          _isLoading = false;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载评论失败: ${e.toString()}')),
        );
      }
    }
  }

  // 获取父评论列表（根据数据源类型处理）
  List<Comment> get _parentComments {
    if (widget.postType == 'technique') {
      // 钓技学堂：直接返回所有评论（已经是父评论，replies在Comment对象内部）
      return _comments;
    } else {
      // 钓友圈：过滤出父评论
      return _comments.where((comment) => 
        comment.parentId == null || comment.parentId == 0 || comment.parentId == comment.id
      ).toList();
    }
  }

  // 获取指定父评论的回复列表（根据数据源类型处理）
  List<Comment> _getRepliesForComment(Comment parentComment) {
    if (widget.postType == 'technique') {
      // 钓技学堂：使用Comment对象内部的replies
      return parentComment.replies ?? [];
    } else {
      // 钓友圈：从平级列表中查找回复
      return _comments.where((comment) => 
        comment.parentId == parentComment.id && comment.id != parentComment.id
      ).toList();
    }
  }


  // 根据parentId查找父评论（支持嵌套结构）
  Comment? _findParentComment(int parentId) {
    // 递归查找评论，支持嵌套结构
    Comment? findInComments(List<Comment> comments) {
      for (var comment in comments) {
        if (comment.id == parentId) {
          return comment;
        }
        // 如果有回复，递归查找
        if (comment.replies != null && comment.replies!.isNotEmpty) {
          final found = findInComments(comment.replies!);
          if (found != null) return found;
        }
      }
      return null;
    }
    
    return findInComments(_comments);
  }


  void _toggleCommentLike(Comment comment) async {
    try {
      final result = await _commentService.toggleCommentLike(
        commentId: comment.id,
        postType: widget.postType,
      );
      
      if (result['success'] == true) {
        setState(() {
          final index = _comments.indexOf(comment);
          if (index != -1) {
            _comments[index] = comment.copyWith(
              isLiked: !comment.isLiked,
              likeCount: comment.isLiked ? comment.likeCount - 1 : comment.likeCount + 1,
            );
          }
        });
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(result['message'] ?? '操作失败')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('操作失败: ${e.toString()}')),
      );
    }
  }

  void _addComment() async {
    if (_commentController.text.trim().isEmpty) return;

    if (_isSubmittingComment) {
      return;
    }

    setState(() {
      _isSubmittingComment = true;
    });

    try {
      final result = await _commentService.addComment(
        postId: widget.postId,
        postType: widget.postType,
        content: _commentController.text.trim(),
        parentId: _replyingToComment?.id,
      );

      final resultMap = result;
      if (resultMap['success'] == true) {
        final commentContent = _commentController.text.trim();
        _commentController.clear();
        
        // 发送WebSocket通知
        await _sendNotification(commentContent);
        
        // 清除回复状态
        setState(() {
          _replyingToComment = null;
          _isReplying = false;
        });
        
        // 关闭底部弹窗
        Navigator.of(context).pop();
        
        // 重新加载评论列表
        _loadComments();
        
        // 通知父组件评论数量变化
        if (widget.onCommentCountChanged != null) {
          widget.onCommentCountChanged!(_comments.length + 1);
        }
        
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(resultMap['message'] ?? '发布成功'),
            duration: Duration(seconds: 1),
          ),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(resultMap['message'] ?? '发布失败')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('发布失败: ${e.toString()}')),
      );
    } finally {
      setState(() {
        _isSubmittingComment = false;
      });
    }
  }

  /// 发送Redis通知
  Future<void> _sendNotification(String commentContent) async {
    try {
      if (_replyingToComment != null) {
        // 这是回复评论的通知
        final targetUserId = _replyingToComment!.userId.toString();
        
        // 发送到Redis通知系统
        await _wsManager.offlineMessageService.sendNotificationToRedis(
          toUserId: targetUserId,
          notificationType: 'comment_reply',
          title: '评论回复',
          content: '有人回复了您的评论：$commentContent',
          senderName: '当前用户', // 这里应该是当前用户的名称
          senderId: 'current_user_id', // 这里应该是当前用户的ID
          targetId: _replyingToComment!.id.toString(),
          targetType: 'comment',
          navigationPath: '/community/${widget.postId}',
          navigationParams: {
            'postId': widget.postId.toString(),
            'commentId': _replyingToComment!.id.toString(),
            'scrollToComment': true,
          },
        );
        
        // 同时通过WebSocket发送实时通知（如果用户在线）
        await _wsManager.sendCommentReplyNotification(
          toUserId: targetUserId,
          commentId: _replyingToComment!.id.toString(),
          replyContent: commentContent,
          postId: widget.postId.toString(),
          postTitle: '钓友圈帖子', // 这里可以传入实际的帖子标题
        );
        
      } else {
        // 这是对帖子的直接评论，需要通知帖子作者
        
        // 发送到Redis通知系统
        await _wsManager.offlineMessageService.sendNotificationToRedis(
          toUserId: 'post_author_id', // 这里需要获取实际的帖子作者ID
          notificationType: 'post_reply',
          title: '帖子回复',
          content: '有人评论了您的帖子：$commentContent',
          senderName: '当前用户',
          senderId: 'current_user_id',
          targetId: widget.postId.toString(),
          targetType: 'post',
          navigationPath: '/community/${widget.postId}',
          navigationParams: {
            'postId': widget.postId.toString(),
            'scrollToComments': true,
          },
        );
        
      }
    } catch (e) {
      // 通知发送失败不影响评论发布流程
    }
  }

  // 开始回复评论
  void _startReply(Comment comment) {
    setState(() {
      _replyingToComment = comment;
      _isReplying = true;
    });
    showCommentInputBottomSheet();
  }

  // 取消回复
  void _cancelReply() {
    setState(() {
      _replyingToComment = null;
      _isReplying = false;
    });
  }

  // 切换评论展开/折叠状态
  void _toggleCommentExpansion(int commentId) {
    setState(() {
      _expandedComments[commentId] = !(_expandedComments[commentId] ?? false);
    });
  }

  // 检查评论是否展开
  bool _isCommentExpanded(int commentId) {
    // 钓技学堂和钓友圈都默认折叠，需要手动展开
    return _expandedComments[commentId] ?? false;
  }

  String _formatTime(dynamic time) {
    DateTime dateTime;
    if (time is String) {
      try {
        dateTime = DateTime.parse(time);
      } catch (e) {
        return time; // 如果解析失败，直接返回原字符串
      }
    } else if (time is DateTime) {
      dateTime = time;
    } else {
      return '未知时间';
    }

    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inMinutes < 1) {
      return '刚刚';
    } else if (difference.inHours < 1) {
      return '${difference.inMinutes}分钟前';
    } else if (difference.inDays < 1) {
      return '${difference.inHours}小时前';
    } else if (difference.inDays < 7) {
      return '${difference.inDays}天前';
    } else {
      return DateFormat('MM-dd').format(dateTime);
    }
  }

  void showCommentInputBottomSheet() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      enableDrag: true,
      isDismissible: true,
      builder: (context) => _buildCommentInputBottomSheet(),
    );
  }

  Widget _buildCommentInputBottomSheet() {
    return StatefulBuilder(
      builder: (BuildContext context, StateSetter setModalState) {
        return Container(
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
          // 顶部拖拽条
          Container(
            margin: const EdgeInsets.only(top: 8, bottom: 16),
            width: 40,
            height: 4,
            decoration: BoxDecoration(
              color: Colors.grey[300],
              borderRadius: BorderRadius.circular(2),
            ),
          ),
          
          // 回复提示
          if (_isReplying && _replyingToComment != null)
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.blue[50],
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.blue[200]!),
              ),
              child: Row(
                children: [
                  Icon(Icons.reply, size: 16, color: Colors.blue[600]),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      '回复 ${_replyingToComment!.user?.nickName ?? "匿名用户"}: ${_replyingToComment!.content.length > 20 ? "${_replyingToComment!.content.substring(0, 20)}..." : _replyingToComment!.content}',
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.blue[700],
                      ),
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      _cancelReply();
                      setModalState(() {});
                    },
                    child: Icon(Icons.close, size: 16, color: Colors.blue[600]),
                  ),
                ],
              ),
            ),
          
          // 输入框区域
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              decoration: BoxDecoration(
                color: Colors.grey[100],
                borderRadius: BorderRadius.circular(20),
              ),
              child: TextField(
                controller: _commentController,
                focusNode: _focusNode,
                decoration: InputDecoration(
                  hintText: _isReplying ? '回复评论...' : '说点什么...',
                  hintStyle: TextStyle(fontSize: 14, color: Colors.grey),
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(horizontal: 8, vertical: 8),
                ),
                maxLines: null,
                autofocus: true,
                onChanged: (text) {
                  setModalState(() {}); // 更新发送按钮状态
                  setState(() {}); // 同时更新主组件状态
                },
              ),
            ),
          ),
          
          // 操作栏
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            child: Row(
              children: [
                // 左侧：表情和照片按钮
                Row(
                  children: [
                    GestureDetector(
                      onTap: () => _toggleEmojiKeyboard(setModalState),
                      child: Container(
                        padding: const EdgeInsets.all(8),
                        child: Icon(
                          _showEmojiPanel ? Icons.keyboard : Icons.emoji_emotions_outlined,
                          color: _showEmojiPanel ? Colors.blue : Colors.grey[600],
                          size: 24,
                        ),
                      ),
                    ),
                    const SizedBox(width: 12),
                    GestureDetector(
                      onTap: _pickImage,
                      child: Container(
                        padding: const EdgeInsets.all(8),
                        child: Icon(
                          Icons.photo_camera_outlined,
                          color: Colors.grey[600],
                          size: 24,
                        ),
                      ),
                    ),
                  ],
                ),
                
                const Spacer(),
                
                // 右侧：发送按钮
                GestureDetector(
                  onTap: _commentController.text.trim().isNotEmpty ? () => _addComment() : null,
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
                    decoration: BoxDecoration(
                      color: _commentController.text.trim().isNotEmpty 
                          ? Colors.blue 
                          : Colors.grey[300],
                      borderRadius: BorderRadius.circular(16),
                    ),
                    child: Text(
                      _isReplying ? '回复' : '发送',
                      style: TextStyle(
                        color: _commentController.text.trim().isNotEmpty 
                            ? Colors.white 
                            : Colors.grey[600],
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          
          // 表情面板
          if (_showEmojiPanel) _buildEmojiPanel(),
          
          // 键盘高度适配 - 只有在显示键盘且不显示表情面板时才适配
          if (!_showEmojiPanel) 
            SizedBox(height: MediaQuery.of(context).viewInsets.bottom),
            ],
          ),
        );
      },
    );
  }

  // 构建表情面板
  Widget _buildEmojiPanel() {
    return Container(
      height: 200,
      padding: const EdgeInsets.symmetric(horizontal: 16),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        border: Border(top: BorderSide(color: Colors.grey[200]!)),
      ),
      child: GridView.builder(
        padding: const EdgeInsets.symmetric(vertical: 12),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 8,
          childAspectRatio: 1,
          crossAxisSpacing: 8,
          mainAxisSpacing: 8,
        ),
        itemCount: _commonEmojis.length,
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () => _insertEmoji(_commonEmojis[index]),
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.grey[200]!),
              ),
              child: Center(
                child: Text(
                  _commonEmojis[index],
                  style: const TextStyle(fontSize: 20),
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  // 插入表情
  void _insertEmoji(String emoji) {
    final text = _commentController.text;
    final selection = _commentController.selection;
    final newText = text.replaceRange(selection.start, selection.end, emoji);
    _commentController.text = newText;
    _commentController.selection = TextSelection.collapsed(
      offset: selection.start + emoji.length,
    );
    setState(() {}); // 更新UI
  }

  // 表情和键盘切换
  void _toggleEmojiKeyboard(StateSetter setModalState) {
    if (_showEmojiPanel) {
      // 当前显示表情面板，切换到键盘
      setModalState(() {
        _showEmojiPanel = false;
      });
      setState(() {
        _showEmojiPanel = false;
      });
      _focusNode.requestFocus(); // 显示键盘
    } else {
      // 当前显示键盘或都不显示，切换到表情面板
      if (_focusNode.hasFocus) {
        _focusNode.unfocus(); // 隐藏键盘
        // 延迟一点时间确保键盘完全隐藏后再显示表情面板
        Future.delayed(const Duration(milliseconds: 200), () {
          if (mounted) {
            setModalState(() {
              _showEmojiPanel = true;
            });
            setState(() {
              _showEmojiPanel = true;
            });
          }
        });
      } else {
        // 键盘没有显示，直接显示表情面板
        setModalState(() {
          _showEmojiPanel = true;
        });
        setState(() {
          _showEmojiPanel = true;
        });
      }
    }
  }

  // 选择图片
  void _pickImage() {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('图片上传功能开发中'),
        duration: Duration(seconds: 1),
      ),
    );
  }

  // 构建单个评论项（支持无限层级嵌套）
  Widget _buildCommentItem(Comment comment, {int level = 0}) {
    // 获取当前评论的回复
    final replies = _getRepliesForComment(comment);
    final hasReplies = replies.isNotEmpty;
    
    return Column(
      children: [
        // 当前评论
        Container(
          margin: EdgeInsets.only(
            left: level * 20.0, // 根据层级缩进
            bottom: 8,
          ),
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: level > 0 ? Colors.grey[50] : Colors.white,
            borderRadius: BorderRadius.circular(12),
            border: Border.all(
              color: level > 0 ? Colors.grey[200]! : Colors.grey[100]!,
              width: 1,
            ),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(level > 0 ? 0.03 : 0.08),
                blurRadius: level > 0 ? 4 : 8,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 头像
              Container(
                width: level > 0 ? 32 : 40,
                height: level > 0 ? 32 : 40,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      blurRadius: 4,
                      offset: const Offset(0, 1),
                    ),
                  ],
                ),
                child: CircleAvatar(
                  radius: level > 0 ? 16 : 20,
                  backgroundImage: comment.user?.avatar != null && comment.user!.avatar!.isNotEmpty
                      ? NetworkImage(comment.user!.avatar!)
                      : null,
                  backgroundColor: Colors.grey[300],
                  child: comment.user?.avatar == null || comment.user!.avatar!.isEmpty
                      ? Icon(
                          Icons.person,
                          size: level > 0 ? 16 : 20,
                          color: Colors.grey[600],
                        )
                      : null,
                ),
              ),
              const SizedBox(width: 12),
              
              // 评论内容区域
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 用户名和时间
                    Row(
                      children: [
                        Text(
                          comment.user?.nickName ?? "匿名用户",
                          style: TextStyle(
                            fontSize: level > 0 ? 13 : 14,
                            fontWeight: FontWeight.w600,
                            color: Colors.grey[800],
                          ),
                        ),
                        const SizedBox(width: 8),
                        Text(
                          _formatTime(comment.createTime),
                          style: TextStyle(
                            fontSize: 11,
                            color: Colors.grey[500],
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 8),
                    
                    // 回复标识（如果是回复评论）
                    if (level > 0 && comment.parentId != null)
                      Container(
                        margin: const EdgeInsets.only(bottom: 8),
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                        decoration: BoxDecoration(
                          color: Colors.blue[50],
                          borderRadius: BorderRadius.circular(6),
                          border: Border.all(
                            color: Colors.blue[100]!,
                            width: 1,
                          ),
                        ),
                        child: RichText(
                          text: TextSpan(
                            children: [
                              TextSpan(
                                text: '回复 ',
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Colors.grey[600],
                                ),
                              ),
                              TextSpan(
                                text: '@${_findParentComment(comment.parentId!)?.user?.nickName ?? "匿名用户"}',
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Colors.blue[700],
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    
                    // 评论内容
                    Text(
                      comment.content,
                      style: TextStyle(
                        fontSize: level > 0 ? 14 : 15,
                        color: Colors.grey[800],
                        height: 1.4,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                    
                    const SizedBox(height: 12),
                    
                    // 操作栏
                    Row(
                      children: [
                        // 点赞按钮
                        GestureDetector(
                          onTap: () => _toggleCommentLike(comment),
                          child: Container(
                            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                            decoration: BoxDecoration(
                              color: comment.isLiked ? Colors.red[50] : Colors.grey[100],
                              borderRadius: BorderRadius.circular(16),
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Icon(
                                  comment.isLiked ? Icons.favorite : Icons.favorite_border,
                                  size: 14,
                                  color: comment.isLiked ? Colors.red[400] : Colors.grey[600],
                                ),
                                if (comment.likeCount > 0) ...[
                                  const SizedBox(width: 4),
                                  Text(
                                    '${comment.likeCount}',
                                    style: TextStyle(
                                      fontSize: 12,
                                      color: comment.isLiked ? Colors.red[400] : Colors.grey[600],
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),
                                ],
                              ],
                            ),
                          ),
                        ),
                        
                        const SizedBox(width: 12),
                        
                        // 回复按钮
                        GestureDetector(
                          onTap: () => _startReply(comment),
                          child: Container(
                            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                            decoration: BoxDecoration(
                              color: Colors.blue[50],
                              borderRadius: BorderRadius.circular(16),
                            ),
                            child: Text(
                              '回复',
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.blue[600],
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ),
                        ),
                        
                        // 展开/折叠按钮（对有回复的评论显示）
                        if (hasReplies) ...[
                          const SizedBox(width: 12),
                          GestureDetector(
                            onTap: () => _toggleCommentExpansion(comment.id),
                            child: Container(
                              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                              decoration: BoxDecoration(
                                color: Colors.orange[50],
                                borderRadius: BorderRadius.circular(16),
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  AnimatedRotation(
                                    turns: _isCommentExpanded(comment.id) ? 0.5 : 0,
                                    duration: const Duration(milliseconds: 200),
                                    child: Icon(
                                      Icons.keyboard_arrow_down,
                                      size: 14,
                                      color: Colors.orange[600],
                                    ),
                                  ),
                                  const SizedBox(width: 4),
                                  Text(
                                    _isCommentExpanded(comment.id) 
                                        ? '收起回复' 
                                        : '${replies.length}条回复',
                                    style: TextStyle(
                                      fontSize: 12,
                                      color: Colors.orange[600],
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        
        // 子评论（递归渲染）
        if (hasReplies && _isCommentExpanded(comment.id))
          ...replies.map((reply) => _buildCommentItem(reply, level: level + 1)),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 评论标题
        Container(
          padding: const EdgeInsets.all(16),
          child: Text(
            '评论 (${_comments.length})',
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w600,
            ),
          ),
        ),
        
        // 评论列表
        if (_isLoading)
          const Center(
            child: Padding(
              padding: EdgeInsets.all(32),
              child: CircularProgressIndicator(),
            ),
          )
        else if (_comments.isEmpty)
          Container(
            padding: const EdgeInsets.fromLTRB(32, 32, 32, 100), // 增加底部padding避免被悬浮操作栏遮挡
            child: const Center(
              child: Text(
                '暂无评论，快来抢沙发吧！',
                style: TextStyle(
                  color: Colors.grey,
                  fontSize: 14,
                ),
              ),
            ),
          )
        else
          ListView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: _parentComments.length,
            itemBuilder: (context, index) {
              final parentComment = _parentComments[index];
              return _buildCommentItem(parentComment, level: 0);
            },
          ),
      ],
    );
  }
}